package com.example.codec;

import io.netty.buffer.ByteBuf;
import org.jboss.marshalling.ByteInput;

import java.io.IOException;

/**
 * <p>  </p>
 *
 * @author Chris
 * @since 2024/3/30 10:25
 */
public class ByteInputAdapter implements ByteInput {

    private final ByteBuf buffer;

    public ByteInputAdapter(ByteBuf byteBuf) {
        this.buffer = byteBuf;
    }

    public ByteBuf getBuffer() {
        return buffer;
    }

    @Override
    public int read() throws IOException {
        if (this.buffer.isReadable()) {
            return this.buffer.readByte() & 0xFF;
        }
        return -1;
    }

    @Override
    public int read(byte[] b) throws IOException {
        return this.read(b, 0, b.length);
    }

    @Override
    public int read(byte[] b, int off, int len) throws IOException {
        final int available = this.available();
        if (available <= 0) {
            return -1;
        }

        len = Math.min(available, len);
        this.buffer.readBytes(b, off, len);
        return len;
    }

    @Override
    public int available() throws IOException {
        return this.buffer.readableBytes();
    }

    @Override
    public long skip(long n) throws IOException {
        n = Math.min(this.buffer.readableBytes(), n);

        this.buffer.readerIndex((int) (buffer.readerIndex() + n));

        return n;
    }

    @Override
    public void close() throws IOException {

    }
}